package com.titleevaluation.service;

import com.titleevaluation.entity.Patent;
import com.titleevaluation.entity.Application;
import com.titleevaluation.repository.PatentRepository;
import com.titleevaluation.repository.ApplicationRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class PatentService {

    private final PatentRepository patentRepository;
    private final ApplicationRepository applicationRepository;

    public PatentService(PatentRepository patentRepository, ApplicationRepository applicationRepository) {
        this.patentRepository = patentRepository;
        this.applicationRepository = applicationRepository;
    }

    public Patent createPatent(Long applicationId, Patent patent) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        patent.setApplication(application);
        patent.setCreatedAt(LocalDateTime.now());
        patent.setUpdatedAt(LocalDateTime.now());
        return patentRepository.save(patent);
    }

    public List<Patent> getPatentsByApplicationId(Long applicationId) {
        return patentRepository.findByApplicationId(applicationId);
    }

    public Optional<Patent> getPatentById(Long id) {
        return patentRepository.findById(id);
    }

    public Patent updatePatent(Long id, Patent patent) {
        Patent existingPatent = patentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Patent not found"));
        
        existingPatent.setSequenceNo(patent.getSequenceNo());
        existingPatent.setPatentName(patent.getPatentName());
        existingPatent.setPatentType(patent.getPatentType());
        existingPatent.setIssuingAuthority(patent.getIssuingAuthority());
        existingPatent.setPatentNo(patent.getPatentNo());
        existingPatent.setCountry(patent.getCountry());
        existingPatent.setInventorCount(patent.getInventorCount());
        existingPatent.setPersonalRank(patent.getPersonalRank());
        existingPatent.setRemarks(patent.getRemarks());
        existingPatent.setUpdatedAt(LocalDateTime.now());
        
        return patentRepository.save(existingPatent);
    }

    public void deletePatent(Long id) {
        patentRepository.deleteById(id);
    }
}

